package vendingMachine.inventory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import vendingMachine.gui.ShoppingCart;
import vendingMachine.gui.ShoppingCartItem;

public class VendingInventory implements IVendingInventory
{
  private IInventoryDatabase inventoryDB;
  private IDispenseAdapter itemDispenser;

  private static VendingInventory uniqueInstance;

  // TODO change to singleton
  public VendingInventory()
  {
    inventoryDB = new InventoryDatabase();
    itemDispenser = new DispenseAdapter();
  }

  public static synchronized VendingInventory getInstance()
  {
    if (uniqueInstance == null)
      uniqueInstance = new VendingInventory();
    else
      System.out.println("VendingInventory already exists");

    return uniqueInstance;
  }

  public ArrayList<Item> getItemList()
  {
    return inventoryDB.createItemList();
  }
  
  public Item getItem(int theID)
  {
    return inventoryDB.getItem(theID);
  }
  
  public int dispenseItemList(ShoppingCart cart) throws IOException
  {
    int error_code = 1;

    Iterator iter = cart.getItemList().iterator();

    while (iter.hasNext())
    {
      ShoppingCartItem sCItem = ((ShoppingCartItem) iter.next());
      Item item = (Item)sCItem.getItem();

      // TODO need to create methods to determine column and row from our
      // database
      // instead of getting it from the shopping cart. We are only interested in
      // ID and
      // quantity from shopping cart.
      int x = item.getColumn();
      int y = item.getRow();
      int ID = item.getID();
      int quantity = sCItem.getQuantity();

      for(int i = 0; i < quantity;i++)
      {
	      if (itemDispenser.dispenseItem(x, y)) // if item was dispensed
	      { // successfully
	        inventoryDB.reduceQuantity(ID, quantity);
	        System.out.println(item.toString());
	      }
	      else
	        error_code = 0;
      }
    }
    System.out.println("Done");
    return error_code;
  }
  public static void main(String[] args)
  {
    VendingInventory invent = new VendingInventory();
    ArrayList<Item> theList = invent.getItemList();
    Iterator theIter = theList.iterator();
    while (theIter.hasNext())
    {
      System.out.println(((Item) theIter.next()).toString());
    }

    ShoppingCart cart = new ShoppingCart();
    cart.addItem(invent.getItem(1000));
    cart.addItem(invent.getItem(1001));
    cart.addItem(invent.getItem(2000));
    cart.addItem(invent.getItem(3000));

    try
    {
      invent.dispenseItemList(cart);
    }
    catch (IOException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

  }
}
